package com.fangcang.elasticsearch;

import java.net.InetAddress;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.joda.time.LocalDateTime;

import com.alibaba.fastjson.JSONObject;

public class ElasticSearchQuery {
	
	static EsQueryService service = new EsQueryService();

	@SuppressWarnings("resource")
	public static void main(String[] args) throws Exception {
//		Settings settings = Settings.builder().put("cluster.name", "es").build();
		TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
				.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
		
		DeleteRequest delRequest = new DeleteRequest("filebeat-2018.11.23", "filebeat", "Xp-tPmcBxRTW63Lsru9_");
		client.delete(delRequest);
//		 addEmploy(client);

		// undateEmployee(client);
		// delEmployee(client);
//		getEmployee(client);

	//searchEmployee(client, "filebeat-2018.11.20");
		
//		List<EsQueryParam> params = new ArrayList<EsQueryParam>();
//		EsQueryParam param = new EsQueryParam();
//		param.setParamCode("country");
//		param.setParamValue("China");
//		param.setMust(true);
//		params.add(param);
		//service.filterSearch(client, params, "company", "employee");
		
		EsQueryParam param = new EsQueryParam();
		param.setIndex("filebeat-2018.11.23");
		param.setIndexType("filebeat");
		param.setField("createTime");
//		param.setFromTime("1542959820499");
//		param.setToTime("1542959860688");
		
		List<Map<String, Object>> result = service.searchByTimes(client, param);
		if(null != result && !result.isEmpty()) {
			for(Map<String, Object> rs : result) {
				System.out.println(JSONObject.toJSONString(rs));
			}
		}
		
		//service.scrollPageSearch(client, "filebeat-2018.11.23");
		client.close();
	}

	public static void addEmploy(TransportClient client) throws Exception {
		XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("name", "赵六").field("age", 36)
				.field("position", "technique History").field("country", "China").field("join_date", LocalDateTime.now().toString())
				.field("salary", "11000").endObject();
		IndexResponse response = client.prepareIndex("company", "employee", "4").setSource(builder).get();
		System.out.println(response.getResult());
	}

	public static void delEmployee(TransportClient client) {
		int i=0;
		for(; i<10;i++) {
			DeleteResponse response = client.prepareDelete("company", "employee", i+"").get();
			System.out.println(response.getResult());
		}
	}

	public static void undateEmployee(TransportClient client) throws Exception {
		XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("name", "lisi").endObject();
		UpdateResponse response = client.prepareUpdate("company", "employee", "6").setDoc(builder).get();
		System.out.println(response.getResult());
	}

	public static void getEmployee(TransportClient client) {
		GetResponse response = client.prepareGet("company", "employee", "6").get();
		System.out.println(response.getSourceAsString());
	}

	public static void searchEmployee(TransportClient client,String index) {
		SearchResponse response = client.prepareSearch(index+"*").execute().actionGet();
		SearchHits searchHits = response.getHits();
		SearchHit[] hits = searchHits.getHits();
		for (SearchHit searchHit : hits) {
			// 获取高亮的字段
			Map<String, Object> sourceAsMap = (Map<String, Object>) searchHit.getSourceAsMap();
			System.out.println(JSONObject.toJSONString(sourceAsMap));
		}
	}

	public static void filterSearch(TransportClient client, String index, String indexType) {
		QueryBuilder qb = QueryBuilders.boolQuery()
				.must(QueryBuilders.constantScoreQuery(QueryBuilders.matchQuery("title", "java")).boost(1f))
				.should(QueryBuilders.constantScoreQuery(QueryBuilders.termQuery("title", "elasticsearch")).boost(5f))
				.should(QueryBuilders.termQuery("title", "hadoop"));

		QueryBuilder fb = QueryBuilders.rangeQuery("age").from(10).to(20);
		SearchResponse searchResponse = client.prepareSearch(index).setTypes(indexType).setQuery(qb).setPostFilter(fb)
				.get();
		SearchHits hits = searchResponse.getHits();
		// long totalHits = hits.getTotalHits();
		SearchHit[] hits2 = hits.getHits();
		for (SearchHit sh : hits2) {
			Map<String, Object> source = sh.getSource();
			String id = sh.getId();
			float score = sh.getScore();
			System.out.println("source:" + source + ",id:" + id + ",score:" + score);
		}

	}

}
